<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    class="demo-ruleForm"
  >
    <el-form-item label="username" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>

    <el-form-item label="pwd" prop="pwd">
      <el-input v-model="ruleForm.pwd" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="loginFn()">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref } from "vue";
import { adminLoginApi, getAdminInfoApi } from "..//../request/api";
import Cookie from "js-cookie";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const state = reactive({
  ruleForm: {
    username: "admin",
    pwd: "123456",
  },
});
const validatePwd = (
  rule: unknown,
  value: string | undefined,
  callback: (msg?: string) => void
) => {
  if (!value) {
    callback("密码不能为空！");
  } else {
    callback();
  }
};

//校验规则
const rules = reactive({
  //单一校验
  username: [{ required: true, message: "用户名必填！", trigger: "blur" }],
  //多项校验
  pwd: [{ required: true, validator: validatePwd, trigger: "blur" }],
});

let { ruleForm } = toRefs(state);
//获取el-form组件对象
let ruleFormRef = ref();
//获取路由对象
let router = useRouter();
//获取项目vuex对象
let store = useStore();

//点击登录按钮触发
const loginFn = () => {
  ruleFormRef.value
    .validate()
    .then(() => {
      console.log("校验通过");
      adminLoginApi({
        password: ruleForm.value.pwd,
        username: ruleForm.value.username,
      }).then((res) => {
        if (res.code === 200) {
          //存储cookie，js-cookie
          Cookie.set("token", res.data.tokenHead + res.data.token, {
            expires: 7,
          });
          //获取用户信息
          store.dispatch("getAdminInfo").then((res) => {
            router.push("/homepage");
          });
          // getAdminInfoApi().then((res) => {
          //   //res.code
          //   if (res.code == 200) {
          //     // res.data.menus;
          //     //存储到vuex
          //     store.commit("updateMenus", res.data.menus);
          //     //跳转首页
          //     // console.log("info is:" + res.code);
          //     router.push("/homepage");
          //   }
          // });
        }
      });
    })
    .catch(() => {
      console.log("校验不通过");
    });
};
</script>

<style lang="less" scoped></style>
